<template>
  <div class="symptom-container">
    <div class="header">
      <h2>{{ partName }}的相关症状</h2>
      <div class="button-group">
        <el-button type="success" @click="goToWebIndex" style="margin-right: 10px">打视频</el-button>
        <el-button @click="goBack" icon="el-icon-back">返回</el-button>
      </div>
    </div>

    <!-- 症状列表 -->
    <div class="symptom-list" v-loading="loading">
      <div class="tags-container" v-if="symptoms.length">
        <el-tag
          v-for="symptom in symptoms"
          :key="symptom.id"
          class="symptom-tag"
          effect="plain"
          type="info"
          @click="selectSymptom(symptom)"
        >
          {{ symptom.symptomName }}
        </el-tag>
      </div>
      <el-empty v-else description="暂无相关症状"></el-empty>

    </div>

    <!-- 聊天界面 -->
    <div class="chat-container">
      <!-- 聊天记录 -->
      <div class="chat-messages" ref="chatMessages">
        <div v-for="(msg, index) in messages"
             :key="index"
             :class="['message', msg.type]">
          <div v-if="!msg.isDoctor" class="message-content">
            {{ msg.content }}
          </div>
          <div v-else class="doctor-card">
            <div class="doctor-header">
              <span class="doctor-name">{{ msg.doctor.realName || '暂无姓名' }}</span>
              <span class="doctor-title">{{ msg.doctor.title || '暂无职称' }}</span>
            </div>
            <div class="doctor-info">
              <p><label>科室：</label>{{ msg.doctor.department || '暂无' }}</p>
              <p><label>专长：</label>{{ msg.doctor.speciality || '暂无' }}</p>
              <p><label>简介：</label>{{ msg.doctor.introduction || '暂无' }}</p>
              <p><label>挂号费：</label>{{ msg.doctor.doctorPrice || '暂无' }}</p>
            </div>
            <el-button type="primary" size="small" @click="viewDoctorDetail(msg.doctor)">
              挂号
            </el-button>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          placeholder="请描述您的症状..."
          :rows="3"
          type="textarea"
          @keyup.enter.native="sendMessage"
        />
        <el-button type="primary" @click="sendMessage" :loading="loading">
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {content, querySymptomByBodyParts} from "@/api/patient/patient.js";

export default {
  name: 'ReceiveSymptoms',
  data() {
    return {
      partId: null,
      partName: '',
      symptoms: [],
      loading: false,
      messages: [
        {
          type: 'ai',
          content: '你好，请详细描述您的病情，我们将会安排适合的医生为你服务'
        }
      ],
      inputMessage: '',
      retryCount: 3,
    }
  },
  watch: {
    // 监听路由参数变化
    '$route.query': {
      handler(newQuery) {
        this.partId = newQuery.partId
        this.partName = newQuery.partName
        if (this.partId) {
          this.getSymptoms()
        }
      },
      immediate: true  // 立即执行一次
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.scrollToBottom()
    })
  },
  methods: {
    async getSymptoms() {
      this.loading = true
      try {
        const response = await querySymptomByBodyParts(this.partId)
        if (response.code === 200) {
          this.symptoms = response.data
        } else {
          this.$message.error(response.msg || '获取症状数据失败')
        }
      } catch (error) {
        console.error('获取症状数据出错:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    async retryMessage(message, retryCount = 3) {
      for (let i = 0; i < retryCount; i++) {
        try {
          const response = await content(message)
          if (response.code === 200) {
            return response
          }
        } catch (error) {
          if (i === retryCount - 1) throw error
          await new Promise(resolve => setTimeout(resolve, 2000)) // 等待2秒后重试
        }
      }
      throw new Error('重试次数已用完')
    },
    // async sendMessage() {
    //   if (!this.inputMessage.trim()) return
    //
    //   const userMessage = this.inputMessage.trim()
    //
    //   // 添加用户消息
    //   this.messages.push({
    //     type: 'user',
    //     content: userMessage
    //   })
    //
    //   this.inputMessage = ''
    //   this.loading = true
    //
    //   try {
    //     const response = await content(userMessage)
    //     console.log('AI响应:', {
    //       code: response.code,
    //       msg: response.msg,
    //       data: response.data
    //     })
    //
    //     if (response.code === 200) {
    //       // 解析返回的 JSON 字符串
    //       const responseData = JSON.parse(response.data)
    //
    //       // 添加 AI 回复
    //       this.messages.push({
    //         type: 'ai',
    //         content: responseData.condition  // 显示 AI 的回复内容
    //       })
    //
    //       // 如果有医生列表，显示推荐医生
    //       if (responseData.doctors && responseData.doctors.length > 0) {
    //         this.messages.push({
    //           type: 'ai',
    //           content: '根据您的症状，为您推荐以下医生：'
    //         })
    //
    //         // 显示医生列表
    //         responseData.doctors.forEach(doctor => {
    //           this.messages.push({
    //             type: 'ai',
    //             isDoctor: true,
    //             doctor: doctor
    //           })
    //         })
    //       }
    //     } else {
    //       throw new Error(response.msg || '请求失败')
    //     }
    //   } catch (error) {
    //     console.error('AI请求失败:', error)
    //
    //     const errorMsg = error.message || '服务暂时不可用'
    //     this.messages.push({
    //       type: 'ai',
    //       content: `抱歉，${errorMsg}`
    //     })
    //     this.$message.error(errorMsg)
    //   } finally {
    //     this.loading = false
    //     this.$nextTick(() => {
    //       this.scrollToBottom()
    //     })
    //   }
    // },
    async sendMessage() {
      if (!this.inputMessage.trim()) return;

      const userMessage = this.inputMessage.trim();
      this.messages.push({
        type: 'user',
        content: userMessage
      });

      this.inputMessage = '';
      this.loading = true;

      try {
        const aiMessage = {
          type: 'ai',
          content: '',
          streaming: true
        };
        this.messages.push(aiMessage);

        // 通过网关访问AI服务
        const eventSource = new EventSource(`/dev-api/ai/ai/chat?message=${encodeURIComponent(userMessage)}`);

        eventSource.onmessage = (event) => {
          try {
            const text = event.data;
            console.log('收到数据:', text);

            if (text === '[complete]') {
              aiMessage.streaming = false;
              eventSource.close();
              this.loading = false;
            } else {
              aiMessage.content += text;
              this.$nextTick(() => {
                this.scrollToBottom();
              });
            }
          } catch (error) {
            console.error('处理消息失败:', error);
          }
        };

        eventSource.onerror = (error) => {
          console.error('EventSource 错误:', error);
          eventSource.close();
          if (aiMessage.content === '') {
            this.messages.pop(); // 移除空的 AI 消息
            this.messages.push({
              type: 'ai',
              content: '抱歉，连接出现异常，请稍后重试'
            });
          }
          this.loading = false;
          this.$modal.msgError('连接异常，请稍后重试');
        };

      } catch (error) {
        console.error('发送消息失败:', error);
        this.messages.push({
          type: 'ai',
          content: '抱歉，服务出现异常，请稍后重试'
        });
        this.$modal.msgError('发送消息失败：' + error.message);
      } finally {
        this.loading = false;
      }
    },
    selectSymptom(symptom) {
      this.inputMessage = `我有${symptom.symptomName}的症状`
    },
    scrollToBottom() {
      const chatMessages = this.$refs.chatMessages
      chatMessages.scrollTop = chatMessages.scrollHeight
    },
    goBack() {
      this.$router.back()
    },
    viewDoctorDetail(doctor) {
      window.open(
        "http://localhost:9204/pay/pay?subject=" +
        doctor.realName +
        "&traceNo=" +
        (Math.floor(Math.random() * 900000) + 100000) +
        "&totalAmount=" +
        doctor.doctorPrice,
        '_self'
      );
    },
    goToWebIndex() {
      this.$router.push({
        path: '/patient/web/index',
        query: {
          from: 'receive'
        }
      })
    },
  }
}

</script>

<style scoped>
.symptom-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.symptom-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chat-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 50vh;  /* 减小聊天区域高度 */
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.message {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  justify-content: flex-start;
}

.user {
  flex-direction: row-reverse;
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  background: #f5f5f5;
  position: relative;
  white-space: pre-line;
}

.user .message-content {
  background: #e3f2fd;
}

.message-content::before {
  content: 'AI';
  position: absolute;
  top: -20px;
  left: 0;
  font-size: 12px;
  color: #666;
}

.user .message-content::before {
  content: '我';
  right: 0;
  left: auto;
}

.chat-input {
  display: flex;
  gap: 10px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chat-input .el-input {
  flex: 1;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.symptom-tag {
  margin: 5px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.symptom-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 医生信息卡片样式 */
.doctor-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 12px;
  margin-top: 8px;
  background: #fff;
}

.doctor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.doctor-name {
  font-size: 16px;
  font-weight: bold;
}

.doctor-title {
  font-size: 14px;
  color: #666;
}

.doctor-info {
  margin-top: 8px;
}

.doctor-info p {
  margin: 4px 0;
}

.doctor-info label {
  font-weight: bold;
}
</style>
